package com.zkx.fssb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkx.fssb.domain.dto.OrderDto;
import com.zkx.fssb.domain.po.OrderDetail;
import com.zkx.fssb.domain.po.Orders;
import com.zkx.fssb.exception.BaseException;
import com.zkx.fssb.mapper.OrderDetailMapper;
import com.zkx.fssb.mapper.OrderMapper;
import com.zkx.fssb.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;



    @Override
    public void customSaveOrder(OrderDto orderDto) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(orderDto,orders);

        orders.setCreateTime(LocalDateTime.now());


        this.save(orders);

    }

    @Override
    public List<Orders> getByStatus(Integer status) {

        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderStatus,status);
        List<Orders> ordersList = this.getBaseMapper().selectList(wrapper);

        return ordersList;



    }

    @Override
    public List<OrderDto> getOrderListByUserIdOrStatus(Orders order) {
        order.setUserId(1);
        if (order.getUserId()==null){
            throw new BaseException("没有用户ID");
        }
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(order.getUserId()!=null,Orders::getUserId,order.getUserId());
        wrapper.eq(order.getOrderStatus()!=null,Orders::getOrderStatus,order.getOrderStatus());

        List<Orders> ordersList = this.getBaseMapper().selectList(wrapper);

        List<OrderDto> orderDtoList = ordersList.stream().map(orders -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orders, orderDto);
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(orders.getOrderId()!=null,OrderDetail::getOrderId,orders.getOrderId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(lambdaQueryWrapper);
            orderDto.setList(orderDetailList);
            return orderDto;
        }).collect(Collectors.toList());
        return orderDtoList;
    }


}
